import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi, getUserInfo, logout as logoutApi } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  const permissions = ref([])
  
  // 计算属性
  const isLoggedIn = computed(() => !!token.value)
  const userName = computed(() => userInfo.value.name || userInfo.value.username || '')
  const userRole = computed(() => userInfo.value.role || 0)
  const roleText = computed(() => {
    const roleMap = { 1: '患者', 2: '医生', 3: '管理员' }
    return roleMap[userRole.value] || '未知'
  })
  
  // 判断是否为管理员
  const isAdmin = computed(() => userRole.value === 3)
  // 判断是否为医生
  const isDoctor = computed(() => userRole.value === 2)
  // 判断是否为患者
  const isPatient = computed(() => userRole.value === 1)
  
  // 操作
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }
  
  const setUserInfo = (info) => {
    userInfo.value = info
    localStorage.setItem('userInfo', JSON.stringify(info))
  }
  
  const setPermissions = (perms) => {
    permissions.value = perms
  }
  
  // 登录
  const login = async (loginForm) => {
    try {
      const response = await loginApi(loginForm)
      if (response.code === 200) {
        setToken(response.data.token)
        setUserInfo(response.data.userInfo)
        if (response.data.permissions) {
          setPermissions(response.data.permissions)
        }
        return response
      }
      throw new Error(response.message || '登录失败')
    } catch (error) {
      throw error
    }
  }
  
  // 获取用户信息
  const fetchUserInfo = async () => {
    try {
      const response = await getUserInfo()
      if (response.code === 200) {
        setUserInfo(response.data.userInfo)
        if (response.data.permissions) {
          setPermissions(response.data.permissions)
        }
        return response.data
      }
      throw new Error(response.message || '获取用户信息失败')
    } catch (error) {
      throw error
    }
  }
  
  // 登出
  const logout = async () => {
    try {
      await logoutApi()
    } catch (error) {
      console.error('登出接口调用失败:', error)
    } finally {
      // 无论接口是否成功，都清除本地数据
      clearUserData()
    }
  }
  
  // 清除用户数据
  const clearUserData = () => {
    token.value = ''
    userInfo.value = {}
    permissions.value = []
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
  
  // 检查权限
  const hasPermission = (permission) => {
    if (isAdmin.value) return true // 管理员拥有所有权限
    return permissions.value.includes(permission)
  }
  
  // 检查角色
  const hasRole = (role) => {
    if (Array.isArray(role)) {
      return role.includes(userRole.value)
    }
    return userRole.value === role
  }
  
  return {
    // 状态
    token,
    userInfo,
    permissions,
    
    // 计算属性
    isLoggedIn,
    userName,
    userRole,
    roleText,
    isAdmin,
    isDoctor,
    isPatient,
    
    // 操作
    setToken,
    setUserInfo,
    setPermissions,
    login,
    fetchUserInfo,
    logout,
    clearUserData,
    hasPermission,
    hasRole
  }
}) 